import { login, key, menuAuth, logout } from '@/api/login-base'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getData, setData } from "@/utils/data-cache";
import router, { resetRouter } from '@/router'
import { passEncrypt } from "@/utils/rsa";

const state = {
  token: getToken(),
  userId: '',
  name: '',
  username: '',
  passExpire: false,
  menuCount: 0,
  companyInfo: null,
  admin: false,
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    if (!!token) {
      setToken(token);
    } else {
      removeToken()
    }
  },
  SET_COMPANY_INFO: (state, data) => {
    state.companyInfo = data
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ADMIN: (state, admin) => {
    state.admin = admin
  },
  SET_USER_NAME: (state, username) => {
    state.username = username
  },
  SET_PASS_EXPIRE: (state, isExpire) => {
    state.passExpire = !!isExpire
  },
  SET_MENU_COUNT: (state, count) => {
    state.menuCount = count
  },
};

const actions = {

  /**
   * 用户登录
   * @param commit
   * @param loginFormData
   * @returns {Promise<any>}
   */
  login({ commit }, loginFormData) {
    const { userName, password, verify, checkToken } = loginFormData;
    return new Promise(async (resolve, reject) => {
      let encryptPass = await passEncrypt(password);
      login({
        userName: userName.trim(),
        password: encryptPass,
        checkCode: verify,
        checkToken: checkToken
      }).then(response => {
        const token = 'Bearer ' + response.token;
        commit('SET_TOKEN', token);
        delete response.token;
        setData('userInfo', response); //本地存储用户信息数据
        resolve()
      }).catch(reject)
    })
  },

  /**
   * 获取用户基本信息
   * 目前后台api登录与获取用户信息为同一接口，为适配多种接口的情况，将userInfo获取拆分为独立方法
   * @param commit
   * @param state
   * @returns {Promise<any>}
   */
  getInfo({ commit }) {
    try {
      let info = JSON.parse(getData('userInfo'));
      commit('SET_ADMIN', info.admin);
      commit('SET_USER_ID', info.userId);
      commit('SET_NAME', info.realName);
      commit('SET_USER_NAME', info.userName);
      commit('SET_PASS_EXPIRE', info.passwdExpire);
      commit('SET_COMPANY_INFO', {
        companyName: info.companyName,
        companyId: info.companyId,
        companyType: info.companyType,
      });
      return info;
    } catch (e) {
      return null;
    }
  },

  /**
   * 系统权限获取
   * 主要为菜单权限，api接口指定有权限的菜单路径
   * @param commit
   * @param state
   * @returns {Promise<any>}
   */
  getSystemAuth({ commit }) {
    return new Promise((resolve, reject) => {
      menuAuth().then(res => {
        commit('SET_MENU_COUNT', res.length || -1);
        resolve(res)
      }).catch(reject)
    })
  },

  /**
   * 登出，清空缓存
   * @param commit
   * @returns {Promise<any>}
   */
  logout({ commit,dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
      });
      setTimeout(() => {
        actions.clearUserAuth({ commit });
        resetRouter();
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      })
    })
  },

  resetLoginStatus({ commit }) {
    actions.clearUserAuth({ commit });
    resetRouter();
    router.push('/login?redirect=' + location.hash.replace('#', ''));
  },

  clearUserAuth({ commit }) {
    commit('SET_TOKEN', '');
    commit('SET_MENU_COUNT', 0);
  },
  setToken({ commit }, token) {
    commit('SET_TOKEN', token);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
